package com.sheledon.flyCat.core.handler;

import com.sheledon.flyCat.common.pojo.MethodDetail;
import com.sheledon.flyCat.core.factory.HttpResponseFactory;
import com.sheledon.flyCat.core.factory.ParameterResolverFactory;
import com.sheledon.flyCat.core.ioc.BeanFactory;
import com.sheledon.flyCat.core.resolver.ParameterResolver;
import com.sheledon.flyCat.network.socket.http.HttpResponse;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author sheledon
 */
public class PostRequestHandler implements RequestHandler {

    @Override
    public HttpResponse handle(MethodDetail methodDetail) {
        Method method = methodDetail.getTargetMethod();
        if (method==null) {
            return HttpResponseFactory.getNotFoundResponse();
        }
        Object targetObject = BeanFactory.getBean(method.getDeclaringClass());
        Parameter [] parameters = method.getParameters();
        List<Object> args = new ArrayList<>(parameters.length);
        for (Parameter parameter : parameters) {
            ParameterResolver resolver = ParameterResolverFactory.get(parameter);
            if (Objects.isNull(resolver)){
                continue;
            }
            Object value = resolver.resolve(methodDetail, parameter);
            args.add(value);
        }
        try {
            Object result = method.invoke(targetObject, args.toArray());
            if (void.class.equals(method.getReturnType())){
                return HttpResponseFactory.getSuccessResponse();
            }
            return HttpResponseFactory.buildSuccessResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return HttpResponseFactory.getErrorResponse();
    }

}
